package cn.xgxd.filter;

import cn.xgxd.config.AuthProperties;
import cn.xgxd.config.JWTUtils;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@Component

public class LoginGlobalFilter implements GlobalFilter , Ordered {
    @Autowired
    private AuthProperties authProperties;

    private  JWTUtils jwtUtils;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断
        if (isAllowPath(request)){
            return chain.filter(exchange);
        }
        //
        // 3.获取token
        List<String> heards = request.getHeaders().get("Authorization");
        String token = null;
        if (heards !=null){
            token = heards.get(0);
        }

        //4.解析token
        Claims claims = null;
        try {
            claims = jwtUtils.parseJWT(token);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        String s = claims.toString();
        //5.传递
        ServerWebExchange exc = exchange.mutate().request(builder -> builder.header("userInfo",s))
                .build();
        //6.放行
        return chain.filter(exc);
    }

    private boolean isAllowPath(ServerHttpRequest request) {
        boolean flag = false;
        //1.放行的路径
//        String method= request.getMethodValue(); //需要判断方法才写
        String path = request.getPath().toString();
        //2.要放行的路径
        for (String excludePath : authProperties.getExcludePaths()) {
            boolean match = antPathMatcher.match(excludePath, path);
            if (match){
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
